package com;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;

import com.manager.FormatoFactory;
import com.manager.ReporteFactory;

import exceptions.FiltroSinDatosException;
import exceptions.InvalidArgumentException;
import exceptions.ReporteSizeException;

public class Request extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {

	private static final long serialVersionUID = -5205559868185253104L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		try {
			ReporteFactory.getInstance().cargarReportes();
			FormatoFactory.getInstance().cargarFormatosReportes();
		} catch (NumberFormatException e) {
			throw new RuntimeException(e);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} catch (InvalidArgumentException e) {
			throw new RuntimeException(e);
		}
		System.out.println("\n*****Finalizada Exitosamente Carga de Reportes *****\n");
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			Reporte reporte = ReporteFactory.getInstance().getReporte(
					request.getParameter("idReporte"));
			reporte.setFormato(request.getParameter("formatoReporte"));
			reporte.setTamanoMaxReporte(request.getParameter("maxSizeReporteCliente"));
			reporte.VerificarParametros(request);
			reporte.generarReporte(response);
		}catch (InvalidArgumentException e) {
			response.sendError(1100,e.getMessage());
			e.printStackTrace();
		} catch (NumberFormatException e) {
			response.sendError(1120,e.getMessage());
			e.printStackTrace();
		} catch (CloneNotSupportedException e) {
			response.sendError(1130,e.getMessage());
			e.printStackTrace();
		} catch (SQLException e) {
			response.sendError(1140,e.getMessage());
			e.printStackTrace();
		} catch (JRException e) {
			response.sendError(1150,e.getMessage());
			e.printStackTrace();
		}catch (FiltroSinDatosException e) {
			response.sendError(1160,e.getMessage());
			e.printStackTrace();
		} catch (ReporteSizeException e) {
			response.sendError(1170,e.getMessage());
			e.printStackTrace();
		} 
	}
}